<template>
        <view class="uni-container">
			<div v-if="$hasRole('manager')">
				开票额度 ：{{stats.rmb}}  已回款 : {{stats.money}}  预估收入 {{stats.estimate}}
			</div>
			<el-dialog title="月流水数据" :visible.sync="dialogFormData" width="80%">
				<p align="center" style="color:#7cb5ec">{{curId}}</p>
				<qiun-data-charts
					type="line"
					:chartData="lineData"
					background="none"
				/>
			</el-dialog>
			<el-dialog title="对账单数据" :visible.sync="dialogFormDzd" width="80%">
				<p align="center" style="color:#7cb5ec">{{curId}}</p>
				<el-table
					highlight-current-row
					:data="dzdData"
					height="400"
					border
					stripe>
				<el-table-column
				  label="版本ID"
				  width="150"
				  sortable
				  prop="edition">
				</el-table-column>
				<el-table-column
				  label="版本名称"
				  width="150"
				  sortable
				  prop="name">
				</el-table-column>
				<el-table-column
				  label="状态"
				  width="100">
				  <template slot-scope="scope">
					<view class="uni-group">
						<div v-if="scope.row.state == 0" style="color:#c7c7c7">待回款</div>
						<div  v-else-if="scope.row.state == 1" style="color:#00cc33">已回款</div>
						<div  v-else style="color:#ff0000">已作废</div>
					</view>
				  </template>
				</el-table-column>
				<el-table-column
				  label="回款金额"
				  width="100"
				  sortable
				  prop="money">
				</el-table-column>
				<el-table-column
				  label="结算金额"
				  sortable
				  width="100"
				  prop="rmb">
				</el-table-column>
				<el-table-column
				  label="回款比例"
				  sortable
				  width="100"
				  prop="rate">
				</el-table-column>
				<el-table-column
				  label="代金券"
				  width="100"
				  sortable
				  prop="voucher">
				</el-table-column>
				<el-table-column
				  label="测试费"
				  width="100"
				  sortable
				  prop="test">
				</el-table-column>
				<el-table-column
				  label="对账人员"
				  width="80"
				  sortable
				  prop="uid">
				</el-table-column>
				<el-table-column
				  label="对账时间"
				  width="150"
				  prop="create_time">
				</el-table-column>
				<el-table-column
				  label="回款时间"
				  width="150"
				  prop="end_time">
				</el-table-column>
				</el-table>
			</el-dialog>
			<el-dialog title="添加对账单" :visible.sync="dialogFormVisible" width="80%">
			  <el-form :model="form">
				<el-form-item label="用户ID" :label-width="formLabelWidth">
				  <el-input v-model="form.uid" autocomplete="off" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="版本名称" :label-width="formLabelWidth">
				  <el-input v-model="form.name" autocomplete="off" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="发行商" :label-width="formLabelWidth">
				  <el-input v-model="form.publisher" autocomplete="off" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="分成比例" :label-width="formLabelWidth">
				  <el-input v-model="form.rate" autocomplete="off" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="通道费" :label-width="formLabelWidth">
				  <el-input v-model="form.tip" autocomplete="off" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="对账金额" :label-width="formLabelWidth">
				  <el-input v-model="form.rmb" autocomplete="off" @change="changeRmb"></el-input>
				</el-form-item>
				<el-form-item label="代金券" :label-width="formLabelWidth">
				  <el-input v-model="form.voucher" autocomplete="off" @change="changeRmb"></el-input>
				</el-form-item>
				<el-form-item label="测试费" :label-width="formLabelWidth">
				  <el-input v-model="form.test" autocomplete="off" @change="changeRmb"></el-input>
				</el-form-item>
				<el-form-item label="结算金额" :label-width="formLabelWidth">
				  <el-input v-model="form.money" autocomplete="off" @change="changeRmb"></el-input>
				</el-form-item>
				<el-form-item label="对账时间" :label-width="formLabelWidth">
				  <div class="block">
					<el-date-picker
					  v-model="form.create_time"
					  type="datetime"
					  placeholder="选择日期时间">
					</el-date-picker>
				  </div>
				</el-form-item>
			  </el-form>
			  <div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="addStatement">确 定</el-button>
			  </div>
			</el-dialog>
			<el-table
				highlight-current-row
				:data="serverData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()) || data.data.des.toLowerCase().includes(search.toLowerCase()))"
				:default-sort = "{prop: 'timeNum', order: 'descending'}"
				height="660"
				border
				stripe
				@sort-change="handleSort">
				<el-table-column
				  fixed = "left"
				  label="版本ID"
				  width="150"
				  prop="name">
				  <template slot="header" slot-scope="scope">
					<el-input
					  v-model="search"
					  size="mini"
					  placeholder="输入关键字搜索"/>
				  </template>
				</el-table-column>
				<el-table-column
				  label="版本名称"
				  sortable
				  width="150"
				  prop="data.des">
				</el-table-column>
				<el-table-column
				  label="状态"
				  sortable
				  width="80">
				  <template slot-scope="scope">
					<view class="uni-group">
						<div v-if="scope.row.data.sync == 1" style="color:#00cc33">同步中</div>
						<div  v-else-if="scope.row.data.sync == 2" style="color:#1989fa">未上线</div>
						<div  v-else-if="scope.row.data.sync == -1" style="color:#ff0000">同步失败</div>
						<div  v-else style="color:#e6a23c">已暂停</div>
					</view>
				  </template>
				</el-table-column>
				<el-table-column
				  label="上线时间"
				  sortable
				  width="120"
				  prop="time">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="总充值"
				  sortable
				  width="120"
				  prop="info.amount">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="预收"
				  sortable
				  width="80"
				  prop="statement.estimate">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="回款"
				  sortable
				  width="80"
				  prop="statement.money">
				</el-table-column>
				<el-table-column
				  label="账号"
				  sortable
				  width="80"
				  prop="info.accNum">
				</el-table-column>
				<el-table-column
				  label="角色"
				  sortable
				  width="80"
				  prop="info.playerNum">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="分成"
				  sortable
				  width="80"
				  prop="data.rate">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="回款比例"
				  sortable
				  width="120"
				  prop="statement.real_estimate">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="ARPU"
				  sortable
				  width="100"
				  prop="info.ARPU">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="开票"
				  sortable
				  width="80"
				  prop="statement.rmb">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="待开"
				  sortable
				  width="80">
				  <template slot-scope="scope">
						{{scope.row.info.amount - scope.row.statement.rmb}}
				  </template>
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="代券"
				  sortable
				  width="80"
				  prop="statement.voucher">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="测试"
				  sortable
				  width="80"
				  prop="statement.test">
				</el-table-column>
				<el-table-column
				  v-if="$hasRole('manager')"
				  label="总收"
				  sortable
				  width="80"
				  prop="statement.all">
				</el-table-column>
				<el-table-column
				  label="底层"
				  sortable
				  width="100"
				  prop="basic">
				</el-table-column>
				<el-table-column
				  label="发行"
				  sortable
				  width="80"
				  prop="publisher">
				</el-table-column>
				<el-table-column
				  label="操作"
				  fixed = "right"
				  width="200">
				  <template slot-scope="scope">
					<view class="uni-group">
						<el-link type="primary"  target ="_blank">
							<el-button size="mini" type="primary" @click="enterBackAdmin(scope.row)">后台</el-button>
						</el-link>
				  <el-dropdown>
					<el-button type="primary" size="mini">
					  设置<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item>
							<button class="uni-button" size="mini" type="primary" @click="getHistoryInfo(scope.row.name)" v-if="$hasRole('manager')">流水记录</button>
						</el-dropdown-item>
						<el-dropdown-item>
							<button class="uni-button" size="mini" type="primary" @click="showStatement(scope.row)" v-if="$hasRole('manager')">添加账单</button>
						</el-dropdown-item>
						<el-dropdown-item>
							<button class="uni-button" size="mini" type="primary" @click="getStatement(scope.row)" v-if="$hasRole('manager')">账单列表</button>
						</el-dropdown-item>
						<el-dropdown-item>
							<el-link type="primary" :href = "scope.row.baota" target ="_blank">
								<button class="uni-button" size="mini" type="primary"  v-if="$hasRole('admin')">宝塔面板</button>
							</el-link>
						</el-dropdown-item>
						<el-dropdown-item>
							<el-link type="primary" :href = "scope.row.baotaTX" target ="_blank">
								<button class="uni-button" size="mini" type="primary"  v-if="$hasRole('admin')">腾讯宝塔</button>
							</el-link>
						</el-dropdown-item>
					</el-dropdown-menu>
					</el-dropdown>
					</view>
				   </template>
				</el-table-column>
			</el-table>
        </view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
    </view>
</template>

<script>
    export default {
        data() {
            return {
				dialogFormVisible : false,
				dialogFormData : false,
				dialogFormDzd : false,
				formLabelWidth : "70px",
				form : {
					uid : "",
					edition : "",
					publisher : "",
					name : "",
					rmb : 0,
					voucher : 0,
					test : 0,
					tip : 0,
					rate : 0,
					money : 0,
					create_time : 0
				},
				stats : {
					all : 0,
					money : 0,
					estimate : 0,
					rmb : 0
				},
				lineData:{
					"categories": [],
					"series": []
				},
				dzdData:[],
				curId : "",
				serverData : [],
                tableData: [],
                // 每页数据量
                pageSize: 10,
                // 当前页
                pageCurrent: 1,
                // 数据总量
                total: 0,
				search: '',
                loading: false
            }
        },
        onLoad() {
			this.form.uid = uni.getStorageSync('lastUsername');
            this.selectedIndexs = []
            this.getBasic()
        },
        methods: {
			//展示结算页面
			showStatement(item){
				this.form.name = item.data.des
				this.form.edition = item.name
				this.form.publisher = this.publishMap[item.data.publisher]
				this.form.tip = item.data.tip
				this.form.rate = item.data.rate
				this.form.rmb = 0
				this.form.voucher = 0
				this.form.test = 0
				this.form.money = 0
				this.form.create_time = Date.now()
				this.dialogFormVisible = true
			},
			//数值改变
			changeRmb(){
				this.form.rmb = Number(this.form.rmb) || 0
				this.form.voucher = Number(this.form.voucher) || 0
				this.form.test = Number(this.form.test) || 0
				this.form.tip = Number(this.form.tip) || 0
				this.form.rate = Number(this.form.rate) || 0
				this.form.voucher = Number(this.form.voucher) || 0
				this.form.money = Number(this.form.money) || 0
			},
			//获取对账单记录
			getStatement(row){
				console.log(row)
				this.request("/getStatement",{edition:row.name},(res) => {
					this.dialogFormDzd = true
					if(res.data){
						var list = []
						for(var i = 0;i < res.data.list.length;i++){
							list[i] = res.data.list[i]
							console.log(list[i])
							list[i]["create_time"] = new Date(Number(list[i]["create_time"])).toLocaleDateString() + " " + new Date(Number(list[i]["create_time"])).toLocaleTimeString()
							if(list[i]["end_time"])
								list[i]["end_time"] = new Date(Number(list[i]["end_time"])).toLocaleDateString() + " " + new Date(Number(list[i]["end_time"])).toLocaleTimeString()
							list[i]["rate"] = Number((list[i]["money"] / (list[i]["rmb"] || 1)).toFixed(5))
							list[i]["name"] = row.data.des
						}
						this.dzdData = list
					}
				})
			},
			//添加对账单
			addStatement(){
				if(!Number.isFinite(this.form.rmb) || !Number.isFinite(this.form.tip) || !Number.isFinite(this.form.rate) || !Number.isFinite(this.form.money)){
					this.$message({
					  message: "数值错误",
					  type: 'error'
					});
					return
				}
				this.form.create_time = new Date(this.form.create_time).getTime()
				this.request("/addStatement",this.form,(res) => {
					this.dialogFormVisible = false
					if(res.data.flag){
						this.$message({
						  message: '添加对账单成功',
						  type: 'success'
						});
						this.getTotalInfo(1)
					}else{
						this.$message({
						  message: res.data.err,
						  type: 'error'
						});
					}
				})
			},
			getHistoryInfo(id){
				this.request("/id_month",{time : Date.now(),num:12,id:id},(res) => {
					this.curId = id
					this.dialogFormData = true
					this.lineData = {"categories":[],"series":[]}
					this.lineData.series.push({"name":id,"data":[]})
					for(var i = res.data.length - 1;i >= 0;i--){
						res.data[i] = JSON.parse(res.data[i])
						var d = new Date(res.data[i].date)
						var str = (d.getMonth() + 1) +"月"
						this.lineData.categories.push(str)
						this.lineData.series[0].data.push(res.data[i].a_pay_amount || 0)
					}
				})
			},
            // 分页触发
            change(e) {
                this.getTotalInfo(e.current)
            },
			//获取底层列表
			getBasic(){
				this.request("/getBasic",{},(res) => {
					this.options = []
					this.basicMap = res.data
					this.getPublish()
				})
			},
			//获取发行列表
			getPublish(){
				this.request("/getPublish",{},(res) => {
					this.publishMap = res.data
					this.getTotalInfo(1)
				})
			},
			//进入后台
			enterBackAdmin(item){
				localStorage.setItem("game_ip",item.data.post)
				localStorage.setItem("game_data",JSON.stringify(item.data))
				window.open(item.data.url)
			},
			//获取版本列表
			getTotalInfo(pageCurrent){
                this.loading = true
                this.pageCurrent = pageCurrent
				this.request("/total_info",{},(res) => {
						var list = []
						if(res.data){
							this.stats = {
								all : 0,
								money : 0,
								estimate : 0,
								rmb : 0
							}
							console.log(res.data)
							for(var i = 0;i < res.data.length;i++){
								res.data[i].data.url = "http://res.linghuanhuyu.com/admin/gameAdmin/index.html#/pages/login/login?game="+res.data[i].data["post"]
								res.data[i]["baota"] = "http://"+res.data[i].data["post"]+":8888"
								res.data[i]["baotaTX"] = res.data[i]["baota"]+"/tencentcloud"
								res.data[i]["timeNum"] = Number(res.data[i]["data"]["time"])
								res.data[i]["time"] = (new Date(res.data[i]["data"]["time"])).toLocaleDateString()
								res.data[i]["basic"] = this.basicMap[res.data[i]["data"]["basic"]]
								res.data[i]["publisher"] = this.publishMap[res.data[i]["data"]["publisher"]]
								res.data[i]["data"]["rate"] = Number(res.data[i]["data"]["rate"]) || 0
								res.data[i]["data"]["tip"] = Number(res.data[i]["data"]["tip"]) || 0
								res.data[i]["data"]["estimate"] = Number(res.data[i]["data"]["estimate"]) || 0
								res.data[i]["info"] = Object.assign({
										amount : 0,
										accNum : 1,
										playerNum : 0
								},res.data[i]["info"])
								for(var j in res.data[i]["info"])
									res.data[i]["info"][j] = Number(res.data[i]["info"][j])
								res.data[i]["info"]["ARPU"] = (res.data[i]["info"].amount/res.data[i]["info"].accNum).toFixed(2)
								
								var statement = {}
								res.data[i]["statement"] = Object.assign({
										all : 0,
										rmb : 0,
										voucher : 0,
										test : 0,
										money : 0.
								},res.data[i]["statement"])
								for(var j in res.data[i]["statement"])
									res.data[i]["statement"][j] = Number(res.data[i]["statement"][j]) || 0
								res.data[i]["statement"]["estimate"] = Math.ceil(((res.data[i]["info"]["amount"] - res.data[i]["statement"]["rmb"]) * (1-res.data[i]["data"]["estimate"]) * res.data[i]["data"]["rate"] * (1 - res.data[i]["data"]["tip"])).toFixed(2)) || 0
								res.data[i]["statement"]["real_estimate"] = (((res.data[i]["statement"]["money"] || 0) / (res.data[i]["statement"]["rmb"] || 1))).toFixed(4)
								this.stats.all += res.data[i]["statement"]["all"] || 0
								this.stats.money += res.data[i]["statement"]["money"] || 0
								this.stats.rmb += res.data[i]["statement"]["rmb"] || 0
								this.stats.estimate += res.data[i]["statement"]["estimate"] || 0
								// if(this.$hasRole('manager') || res.data[i].data.sync == 1)
								list.push(res.data[i])
							}
							this.stats.all = Math.ceil(this.stats.all)
							this.stats.money = Math.ceil(this.stats.money)
							this.stats.estimate = Math.ceil(this.stats.estimate)
							for(var i = 0;i < list.length;i++){
								for(var j = i+1;j < list.length;j++){
									if(list[i].data.time < list[j].data.time){
										var tmp = list[i]
										list[i] = list[j]
										list[j] = tmp
									}
								}
							}
						}
						list.sort(function(a,b){
							return  a.data.sync < b.data.sync || (a.data.sync == b.data.sync && a.data.time < b.data.time) ? 1 : -1
						})
						this.serverData = list
						this.total = list.length
					this.tableData = this.serverData.slice((this.pageCurrent-1)*this.pageSize,this.pageCurrent*this.pageSize)
					console.log(this.serverData)
					this.loading = false
				})
			},
            // request请求
            request(path,options,success) {
				this.$axios.post(path,options)//传参
				.then(function(res){
					  success(res)
				})
				.catch(function(err){
					  console.log("请求失败233");
				});
            }
        }
    }
</script>

<style>
	/* #ifndef H5 */
	page {
		padding-top: 85px;
	}
	::-webkit-scrollbar-thumb{
		background:#e5e5e5;
		border-radius: 10px;
	}
	/* #endif */
</style>
